package library.hibernate.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import library.hibernate.dao.AbstractDAO;

@Transactional(readOnly = true)
@Repository
public class AbstractDAOImpl<E, I extends Serializable> implements AbstractDAO<E, I> {

	private Class<E> entityClass;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	protected AbstractDAOImpl(){
		
	}
	
	protected AbstractDAOImpl(Class<E> entityClass){
		this.entityClass = entityClass;
	}
	
	
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	
	public E findById(I id) {
		return (E) getCurrentSession().get(entityClass, id);
	}
	
	@Transactional(readOnly = false)
	public void saveOrUpdate(E e) {
		getCurrentSession().saveOrUpdate(e);
	}

	@Transactional(readOnly = false)
	public void delete(E e) {
		getCurrentSession().delete(e);
	}

	public List<E> findByCriteria(Criterion criterion) {
		Criteria criteria = getCurrentSession().createCriteria(entityClass);
		criteria.add(criterion);
		return criteria.list();
	}

}
